package tw.asap.plus.ui.activity;

import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPopupWindow;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import tw.asap.plus.R;
import tw.asap.plus.common.ConstValue;
import tw.asap.plus.entity.request.AddAddressRequest;
import tw.asap.plus.entity.request.AddressDelRequest;
import tw.asap.plus.entity.request.CommonRequestParams;
import tw.asap.plus.entity.request.ModifyAddressRequest;
import tw.asap.plus.entity.response.AddAddress;
import tw.asap.plus.entity.response.Address;
import tw.asap.plus.entity.response.CityList;
import tw.asap.plus.entity.response.ResponseDataWrapper;
import tw.asap.plus.network.config.HRetrofitCreator;
import tw.asap.plus.network.service.UserService;
import tw.asap.plus.ui.AsapBaseActivity;
import tw.asap.plus.ui.custom.AppBar;
import tw.asap.plus.utils.ScreenUtil;
import tw.asap.plus.utils.Toaster;

/**
 * Created by Yax.
 * Date: 15/11/14
 * Time: 下午4:02
 * Description:
 */
public class AddressEditActivity extends AsapBaseActivity implements View.OnClickListener {

    @InjectView(R.id.appbar)
    AppBar appbar;
    @InjectView(R.id.ed_name)
    EditText edName;
    @InjectView(R.id.checkbox_man)
    CheckBox checkboxMan;
    @InjectView(R.id.checkbox_female)
    CheckBox checkboxFemale;
    @InjectView(R.id.ed_mobile)
    EditText edMobile;
    @InjectView(R.id.ed_city)
    TextView edCity;
    @InjectView(R.id.ed_area)
    TextView edArea;
    @InjectView(R.id.ed_detail)
    EditText edDetail;

    Address oldAddress;
    @InjectView(R.id.ll_address)
    LinearLayout llAddress;
    @InjectView(R.id.del)
    TextView del;
    @InjectView(R.id.tv_confirm)
    TextView tvConfirm;
    private boolean isDefault;
    OptionsPopupWindow citySelector;
    private ArrayList<CityList> citylist = new ArrayList<>();
    private ArrayList<String> citys = new ArrayList<>();
    ArrayList<String> region = new ArrayList<>();
    CityList currentCity;
    CityList.RegionsEntity currentRegions;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address_edit);
        ButterKnife.inject(this);
        appbar.setRightTitle(getString(R.string.save), this);
        checkboxMan.setOnClickListener(this);
        checkboxFemale.setOnClickListener(this);
        tvConfirm.setOnClickListener(this);
        tvConfirm.setVisibility(View.VISIBLE);
        getCityList();
        oldAddress = getIntent().getParcelableExtra("ADDRESS");
        if (oldAddress != null) {
            del.setVisibility(View.VISIBLE);
            del.setOnClickListener(this);
            appbar.setTitle(getString(R.string.add_new_address));
            isDefault = oldAddress.getIs_default().equals("1");
            if (isDefault) {
                tvConfirm.setVisibility(View.GONE);
            }
            fillData(oldAddress);
        }
    }

    private void fillData(Address address) {
        edName.setText(address.getName());
        checkboxMan.setChecked(address.getSex().equals("0"));
        checkboxFemale.setChecked(address.getSex().equals("1"));
        edMobile.setText(address.getMobile());
        edCity.setText(address.getArea());
        edArea.setText(address.getArea());
        edDetail.setText(address.getAddress());
    }

    private Address checkParams() {
        if (TextUtils.isEmpty(edName.getText())) {
            edName.setError(getString(R.string.address_contact_not_null));
            edName.requestFocus();
            return null;
        }
        if (TextUtils.isEmpty(edMobile.getText())) {
            edMobile.setError(getString(R.string.address_mobile_not_null));
            edMobile.requestFocus();
            return null;
        }
        if (TextUtils.isEmpty(edCity.getText())) {
            edCity.setError(getString(R.string.address_city_not_null));
            return null;
        }
        if (TextUtils.isEmpty(edArea.getText())) {
            edArea.setError(getString(R.string.address_area_not_null));
            return null;
        }
        if (TextUtils.isEmpty(edDetail.getText())) {
            edDetail.setError(getString(R.string.address_detail_not_null));
            edDetail.requestFocus();
            return null;
        }

        Address newAddress = new Address();
        newAddress.setName(edName.getText().toString());
        newAddress.setMobile(edMobile.getText().toString());
        newAddress.setArea(edCity.getText().toString().concat(edArea.getText().toString()));
        newAddress.setAddress(edDetail.getText().toString());
        newAddress.setSex(checkboxMan.isChecked() ? "0" : "1");
        newAddress.setIs_default(isDefault ? "1" : "0");
        newAddress.setAddrid(oldAddress == null ? "" : oldAddress.getAddrid());
        return newAddress;
    }

    @OnClick(R.id.ed_city)
    protected void selectCity() {
        citySelector = new OptionsPopupWindow(this);
        citySelector.setPicker(citys);
        citySelector.setOnoptionsSelectListener((options1, option2, options3) -> {
            edCity.setText(citys.get(options1));
            currentCity = citylist.get(options1);
        });

        citySelector.showAtLocation(edCity, Gravity.BOTTOM, 0, getPickerYPosition());
    }

    private int getPickerYPosition() {
        if (!ScreenUtil.checkDeviceHasNavigationBar(this)) {
            return ScreenUtil.getNavigationBarHeight(this);
        } else {
            return 0;
        }
    }

    @OnClick(R.id.ed_area)
    protected void selectArea() {
        if (currentCity == null) {
            Toaster.s(this, getString(R.string.select_city_first));
        } else {
            citySelector.setPicker(getRegionList(currentCity));
            citySelector.setOnoptionsSelectListener((options1, option2, options3) -> {
                edArea.setText(region.get(options1));
                currentRegions = currentCity.getRegions().get(options1);
            });
            citySelector.showAtLocation(edArea, Gravity.BOTTOM, 0, getPickerYPosition());
        }
    }


    private ArrayList<String> getRegionList(CityList city) {
        region.clear();
        for (CityList.RegionsEntity regionsEntity : city.getRegions()) {
            region.add(regionsEntity.getRegion_name());
        }
        return region;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_navigation_header_right:
                Address newAddress = checkParams();
                if (newAddress != null) {
                    if (oldAddress != null) {
                        modifyAddress(newAddress);
                    } else {
                        addNewAddress(newAddress);
                    }
                }

                break;
            case R.id.checkbox_man:
                checkboxFemale.setChecked(false);
                break;
            case R.id.checkbox_female:
                checkboxMan.setChecked(false);
                break;
            case R.id.del:
                delAddress();
                break;
            case R.id.tv_confirm:
                tvConfirm.setText(R.string.deault_address);
                isDefault = true;
                break;
        }
    }

    private void delAddress() {
        HRetrofitCreator creator = HRetrofitCreator.getInstance();
        Observable.create(new Observable.OnSubscribe<ResponseDataWrapper>() {
            @Override
            public void call(Subscriber<? super ResponseDataWrapper> subscriber) {
                UserService service = creator.getService(UserService.class);
                subscriber.onNext(service.delAddress(new AddressDelRequest(oldAddress.getAddrid())));
                subscriber.onCompleted();
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<ResponseDataWrapper>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ResponseDataWrapper address) {
                        if (address.respcd.equals(ConstValue.RESPCD)) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(AddressEditActivity.this);
                            builder.setMessage(getString(R.string.del_sucess));
                            builder.setPositiveButton("OK", (dialog, which) -> {
                                setResult(RESULT_OK);
                                AddressEditActivity.this.finish();
                            }).show();
                        } else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(AddressEditActivity.this);
                            builder.setMessage(address.resperr);
                            builder.setPositiveButton("OK", (dialog, which) -> {
                            }).show();
                        }
                    }
                });
    }

    private void addNewAddress(Address newAddress) {
        HRetrofitCreator creator = HRetrofitCreator.getInstance();
        Observable.create(new Observable.OnSubscribe<ResponseDataWrapper<AddAddress>>() {
            @Override
            public void call(Subscriber<? super ResponseDataWrapper<AddAddress>> subscriber) {
                UserService service = creator.getService(UserService.class);
                subscriber.onNext(service.addAddress(new AddAddressRequest(newAddress)));
                subscriber.onCompleted();
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<ResponseDataWrapper<AddAddress>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ResponseDataWrapper<AddAddress> address) {
                        if (address.respcd.equals(ConstValue.RESPCD)) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(AddressEditActivity.this);
                            builder.setMessage(getString(R.string.address_add_success));
                            builder.setPositiveButton("OK", (dialog, which) -> {
                                setResult(RESULT_OK);
                                AddressEditActivity.this.finish();
                            }).show();
                        } else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(AddressEditActivity.this);
                            builder.setMessage(address.resperr);
                            builder.setPositiveButton("OK", (dialog, which) -> {
                            }).show();
                        }
                    }
                });
    }

    private void modifyAddress(Address newAddress) {
        HRetrofitCreator creator = HRetrofitCreator.getInstance();
        Observable.create(new Observable.OnSubscribe<ResponseDataWrapper<AddAddress>>() {
            @Override
            public void call(Subscriber<? super ResponseDataWrapper<AddAddress>> subscriber) {
                UserService service = creator.getService(UserService.class);
                subscriber.onNext(service.modifyAddress(new ModifyAddressRequest(newAddress)));
                subscriber.onCompleted();
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<ResponseDataWrapper<AddAddress>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ResponseDataWrapper<AddAddress> address) {
                        if (address.respcd.equals(ConstValue.RESPCD)) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(AddressEditActivity.this);
                            builder.setMessage(getString(R.string.address_modify_success));
                            builder.setPositiveButton("OK", (dialog, which) -> {
                                setResult(RESULT_OK);
                                AddressEditActivity.this.finish();
                            }).show();
                        } else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(AddressEditActivity.this);
                            builder.setMessage(address.resperr);
                            builder.setPositiveButton("OK", (dialog, which) -> {
                            }).show();
                        }
                    }
                });
    }


    private void getCityList() {
        HRetrofitCreator creator = HRetrofitCreator.getInstance();
        Observable.create(new Observable.OnSubscribe<ResponseDataWrapper<List<CityList>>>() {
            @Override
            public void call(Subscriber<? super ResponseDataWrapper<List<CityList>>> subscriber) {
                UserService service = creator.getService(UserService.class);
                subscriber.onNext(service.getCityList(new CommonRequestParams()));
                subscriber.onCompleted();
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<ResponseDataWrapper<List<CityList>>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ResponseDataWrapper<List<CityList>> address) {
                        if (address.respcd.equals(ConstValue.RESPCD)) {
                            citylist.addAll(address.data);
                            for (CityList cityList : citylist) {
                                citys.add(cityList.getRegion_name());
                            }
                        } else {
                            Toaster.s(AddressEditActivity.this, address.resperr);
                        }
                    }
                });
    }

}
